<?php
Globals::requireClass('Controller');
Globals::requireModel('Acl');
Globals::requireModel('Log');
Globals::requireTable('User');

class AdminController extends Controller
{
	public static $defaultConfig = array(
		'viewEnabled'	=> true,
		'layoutEnabled'	=> true,
	);
	
	protected $acl;
	protected $log;
	protected $userInfo;
	protected $hasPrivilege;
	protected $userTable;
	
	public function __construct($config = null, $auth = false)
	{
		parent::__construct($config);
		
		$this->acl = new AclModel($config);
		$this->log = new LogModel($config);
		
		$this->userTable = new UserTable($config);
		
		if ($auth)
			$this->auth($auth);
	}
	
	public function indexAction()
	{
		$this->redirectToController();
	}
	
	protected function auth($resourcename = null)
	{
		@session_start();
		header('Cache-Control: private,must-revalidate');
		
		if (!isset($_SESSION['userInfo']))
			$this->redirectToController('login');
		
		$this->userInfo = $_SESSION['userInfo'];
		
		if (is_string($resourcename))
		{
			if (!$this->acl->isAllowed($this->userInfo['groupid'], $resourcename))
				Globals::error($this->acl->getMessage());
		}
		
		$this->hasPrivilege = $this->acl->isAllowed($this->userInfo['groupid'], 'privilege');
	}
	
	protected function log($message)
	{
		$this->log->log($message, isset($this->userInfo['id']) ? $this->userInfo['id'] : null);
	}
	
	protected function out()
	{
		if($this->view){
			if($this->layout){
				$this->layout->controller	= $this->controller;
				$this->layout->acl			= $this->acl;
				$this->layout->userInfo		= $this->userInfo;
				$this->layout->hasPrivilege	= $this->hasPrivilege;
			}
			$this->view->acl			= $this->acl;
			$this->view->userInfo		= $this->userInfo;
			$this->view->hasPrivilege	= $this->hasPrivilege;
		}
		parent::out();
	}
	
	protected function setDate()
	{
		$date = $this->getParam('date');
		$time = $date ? strtotime($date) : null;
		$now  = time();
		
		if (!$time || $time > $now - 3600 * 24)
			$time = $now - 3600 * 24;
		
		$date = date('Y-m-d', $time);
		$time = strtotime($date);
		
		$this->layout->date	= $date;
		$this->view->date	= $date;
		
		$dates = array(
			date('Y-m-d', strtotime('-1day', $now)),
			date('Y-m-d', strtotime('-2days', $now)),
			date('Y-m-d', strtotime('-3days', $now))
		);
		
		if (date('Ymd', $time) < date('Ymd', $now - 3600 * 24))
			$dates[] =  date('Y-m-d', strtotime('+1day', $time));
		
		$dates[] =  date('Y-m-d', $time);
		$dates[] =  date('Y-m-d', strtotime('-1day', $time));
		
		$this->view->dates = array_unique($dates);
		
		return $time;
	}
}

Config::extend('AdminController', 'Controller');
